const express = require('express');
const { auth, authorize } = require('../middleware/auth');
const validate = require('../middleware/validate');
const foodValidation = require('../validators/food.validator');
const foodController = require('../controllers/food.controller');
const searchHistoryController = require('../controllers/searchHistory.controller');

const router = express.Router();

// 获取全部食物列表
router.get('/all', auth(), validate(foodValidation.getAllFoods), foodController.getAllFoods);

// 搜索和筛选食物
router.get('/search', auth(), validate(foodValidation.searchFoods), foodController.searchFoods);

// 获取用户搜索历史 - 具体路径放在通配符路由前面
router.get('/search-history', auth(), searchHistoryController.getUserSearchHistory);

// 清空用户搜索历史
router.delete('/search-history', auth(), searchHistoryController.clearSearchHistory);

// 获取所有食物分类
router.get('/categories', auth(), foodController.getAllFoodCategories);

// 更新食物分类排序
router.patch('/categories/order', 
  auth(), 
  authorize(['manageContent']), 
  validate(foodValidation.updateCategoriesOrder), 
  foodController.updateCategoriesOrder
);

// 创建食物分类
router.post('/categories', 
  auth(), 
  authorize(['manageContent']), 
  validate(foodValidation.createFoodCategory), 
  foodController.createFoodCategory
);

// 更新食物分类
router.post('/update-category', auth(), validate(foodValidation.updateFoodCategory), foodController.updateFoodCategory);

// 编辑食物分类
router.patch('/categories/:categoryId', 
  auth(), 
  authorize(['manageContent']), 
  validate(foodValidation.editFoodCategory), 
  foodController.editFoodCategory
);

// 删除食物分类
router.delete('/categories/:categoryId', 
  auth(), 
  authorize(['manageContent']), 
  validate(foodValidation.deleteFoodCategory), 
  foodController.deleteFoodCategory
);

// 获取食物详情 - 通配符路由需要放在最后
router.get('/:foodId', auth(), validate(foodValidation.getFoodById), foodController.getFoodById);

// 添加食物
router.post(
  '/',
  auth(),
  authorize(['manageContent']),
  validate(foodValidation.createFood),
  foodController.createFood
);

// 删除食物
router.delete(
  '/:foodId',
  auth(),
  authorize(['manageContent']),
  validate(foodValidation.getFoodById), // Reusing validator that checks for foodId in params
  foodController.deleteFood
);

module.exports = router;